<template>
  <article v-if="prodInfo" class="c-p">
    <section class="c-p c-maxh440 c-minh360 c-text-hidden c-pz2" @click.stop="clickLiveCover" v-show="!isPlayingVideo||isPlayEndVideo">
      <img class="c-w100" :src="$addXossFilter(prodInfo.cover, require('@/assets/defult270.png'))" alt="" />
      <!-- 视频播放按钮 -->
      <div class="c-translucent-balck60 c-pa  c-p-l0 c-p-t0 c-p-r0 c-h c-flex-column c-aligni-center c-justify-center" v-if="prodInfo.videoIntroUrl">
        <i class="iconfont icon-bofang3 c-fc-white c-fs100" v-if="!isPlayingVideo&&!isPlayEndVideo"></i>
        <div v-if="isPlayEndVideo">
          <div class="c-fs20 c-fc-white c-textAlign-c">视频已结束播放</div>
          <div class="c-hh50 c-bg-white c-br24 c-flex-row c-aligni-center c-ph12 c-fc-white c-fs20 theme-bg c-mt30" v-if="
            liveInfo.status!= 4&&liveInfo.status != 3&&liveInfo.isBuyed == 1 && liveInfo.permissionType != 45" @click.stop="cvoverLiveRoom">
            <div class="iconfont c-fs20 c-mr8">&#xe7ba;</div>{{prodInfo.liveStatus==2?'继续观看回放':'继续观看直播'}}
          </div>
          <div class="c-flex-row c-aligni-center c-fc-white c-mt30 c-fs20 c-justify-center" @click.stop="clickLiveCover">
            <div class="iconfont c-fs20 c-mr8 " >&#xe7b8;</div>重播
          </div>
        </div>
      </div>
      <!-- 直播状态 -->
      <div v-if="isShowLiveStatus" class="c-p-l24 c-fs20 c-fc-white c-p-t20 c-pa c-ph12 c-hh32 c-flex-row c-flex-center c-br6 c-text-hidden" :class="LIVE_STATUS_CLASS_MAP[prodInfo.liveStatus]">
        {{LIVE_STATUS_MAP[prodInfo.liveStatus]}}
      </div>
      <!-- 购买信息 -->
      <div class="c-pa c-p-l24 c-p-t64" v-if="showBuySwiper && !isPlayingVideo">
        <buy-inforswiper :swiperList='buySwiperList'></buy-inforswiper>
      </div>
      <!-- 预约 -->
      <div v-if="prodInfo.isShowRemind == 1 && moduleType == 2" class="live-start c-pa c-p-b0 c-p-l0 c-p-r0 c-pz10 c-flex-row c-justify-sb c-aligni-center c-translucent-balck30 c-pl24 c-pr24 c-hh72">
        <div class="c-flex-row c-aligni-center c-fc-white c-fs20">
          预约直播，方便及时接收开播通知
        </div>
        <div @click.stop="startNock" class="c-hh40 c-bg-white c-br20 c-flex-row c-aligni-center c-ph12 theme-fc c-fs20">
          <span class="c-fs20 c-fw-b">{{isSet==1?(personalSet?'取消预约':'取消提醒'):(personalSet?'立即预约':'开播提醒')}}</span>
        </div>
      </div>
      <div v-if="moduleType == 1 && prodInfo.liveStatus == 0 && liveStartDownCount" class="live-start c-pa c-p-b0 c-p-l0 c-p-r0 c-pz10 c-flex-row c-justify-sb c-aligni-center c-translucent-balck30 c-pl24 c-pr24 c-hh72">
        <div class="c-flex-row c-aligni-center c-fc-white c-fs20">
          <div>距离开播：</div>
          <div>
            <span class="c-inlineblack c-textAlign-c time-style">{{ liveStartDownCount.dayNum }}</span>
            <span class="c-ph10">天</span>
            <span class="c-inlineblack c-textAlign-c  time-style">{{ liveStartDownCount.hourNum }}</span>
            <span class="c-ph10">时</span>
            <span class="c-inlineblack c-textAlign-c  time-style">{{ liveStartDownCount.minuteNum }}</span>
            <span class="c-ph10">分</span>
            <span class="c-inlineblack c-textAlign-c  time-style">{{ liveStartDownCount.secondsNum }}</span>
            <span class="c-ph10">秒</span>
          </div>
        </div>
        <div v-if="prodInfo.isShowRemind" @click.stop="startNock" class="c-hh40 c-bg-xblue c-br20 c-flex-row c-aligni-center c-ph12 c-fc-white c-fs20">
          <span class="c-fs20 c-fc-white">{{ isSet == 1 ? (personalSet ? '取消预约' : '取消提醒') : personalSet ? '立即预约' : '开播提醒' }}</span>
        </div>
      </div>

    </section>
    <section v-if="prodInfo.videoIntroUrl" class="c-w100 c-hh360 " id="liveVideoIntroParent" :class="!isPlayingVideo ? 'c-pa c-p-t0 c-pz1':''">
    </section>
    <div v-if="isShowFixedBook" @click.stop="startNock" class="c-pf c-p-r0 c-p-t190 c-hh44 c-br-tl24 c-br-bl24 c-ph10 c-flex-row c-flex-center c-pz101 promote-bg">
      <span class="iconfont c-fs22 theme-fc">&#xe62c;</span>
      <div class="c-fs20 c-ml4 theme-fc">{{isSet==1?(personalSet?'取消预约':'取消提醒'):(personalSet?'立即预约':'开播提醒')}}</div>
    </div>
    <subscribe-qrcode ref="subscribeQrcode" @getChange="getChange"></subscribe-qrcode>
    <cj-popup v-model="showBookSuccess" get-container="body" :closeable="true" close-icon-position="bottom-center" close-icon="icon-shanchu" @closed="showBookSuccess = false">
      <div class="c-ww500 c-center c-p c-bg-white c-br16 c-pb40">
        <img src="@/assets/i/wap/live/book_nextlive.png" alt="" />
        <div class="c-alignc-center c-flex-row c-justify-center">
          <div class="c-pb44 c-pt20 c-fs24 c-fc-xblack c-ww394">
            您已预约成功，快分享直播给好友，邀请好友一起看!
          </div>
        </div>
        <div @click="spreadInvite" class="c-fc-white c-fs28 c-ww280 c-hh64 c-lh64 c-textAlign-c c-bg-xblue c-center c-br36">立即分享</div>
      </div>
    </cj-popup>
  </article>
</template>
<script>
import { utilJs } from "@/utils/common.js";
import buyInforswiper from '@/components/templates/buyInforswiper';
import subscribeQrcode from "@/components/templates/live/subscribeQrcode.vue";
import { getXgplayer, destoryPlayer } from "@/utils/xgplayerJs.js";
const LIVE_STATUS_CLASS_MAP = {
  "0": "c-bg-lred",
  "1": "c-bg-vgreen",
  "2": "c-bg-xlyellow",
  "3": "c-bg-b3",
  "4": "c-bg-b3",
  "5": "c-bg-b3",
}
const LIVE_STATUS_MAP = {
  0: "直播预告",
  1: "正在直播",
  2: "直播回放",
  3: "直播结束",
  4: "已过期"
};
export default {
  name: "LiveDetailCover",
  directives: {
  },
  components: {
    buyInforswiper,
    subscribeQrcode,
  },
  inject: ['goLiveRoom'],
  props: {
    moduleType:{
      type:Number,
      default:1 //1公开课 2 独立直播间
    },
    liveInfo:{
      type: Object,
      default: {}
    }
  },
  computed: {
    isShowLiveStatus() {
      //公开课 || (直播间 && 直播中) 才显示直播状态
      const isShow = this.moduleType == 1 || (this.moduleType == 2 && this.prodInfo && this.prodInfo.liveStatus == 1)
      return isShow;
    },
    isShowFixedBook() {
      const isShowRemind = this.isPlayingVideo && this.prodInfo.isShowRemind == 1;
      //直播间 || 公开课 && 直播未开始 && 直播开始倒计时存在
      const canShow = this.moduleType == 2 || (this.moduleType == 1 && this.prodInfo && this.prodInfo.liveStatus == 0 && this.liveStartDownCount);
      return isShowRemind && canShow
    }
  },
  data() {
    return {
      LIVE_STATUS_CLASS_MAP: Object.freeze(LIVE_STATUS_CLASS_MAP),
      LIVE_STATUS_MAP: Object.freeze(LIVE_STATUS_MAP),
      buySwiperList: [],
      showBuySwiper: false,
      isPlayingVideo: false,
      isPlayEndVideo: false,
      liveStartDownCount: null,
      prodInfo: null,
      personalSet:false,
      showBookSuccess:false,
      isSet:0,
    }
  },
  methods: {
    cvoverLiveRoom() {
      this.$emit('cvoverLiveRoom')
    },
    spreadInvite() {
      this.showBookSuccess = false;
      this.$emit('spreadInvite')
    },
    // 关闭关注二维码的时候，延迟获取是否订阅，防止微信通知太晚状态不准确
    getChange(isbottom) {
      setTimeout(() => {
        this.nockBottom(isbottom)
        this.getLiveRemind()
      }, 500);
    },
    //获取订阅信息 isSet 1 已订阅 0未订阅
    getLiveRemind() {
      utilJs.getMethod(`${global.apiurl}liveFlow/getLiveRemind/${this.prodInfo.prodId}?moduleType=${this.moduleType}`, res => {
        this.isSet = res.isSet
        this.$emit('liveRemind', this.isSet)
      });
    },
    //订阅提醒
    startNock(isbottom) {
      if (this._isClicking) {
        return
      }
      this._isClicking = true;
      this.setType = this.isSet == 1 ? 2 : 1;
      let data = {
        type: this.setType,
        moduleType: this.moduleType, //1公开课 2 独立直播间
      }
      utilJs.postMethod(`${global.apiurl}liveFlow/setLiveRemind/${this.prodInfo.prodId}`, data, res => {
        this._isClicking = false;
        if (res.mpQrcode) {
          this.$refs.subscribeQrcode.public_openQrcode(res.mpQrcode, isbottom);
          return;
        }
        if (!res.status) {
          this.$showCjToast({
            text: '设置失败',
            type: 'warn',
          });
          this.nockBottom(isbottom)
          return;
        }
        this.getLiveRemind()
        let tipText = this.setType == 1 ? (utilJs.isAndroidApp() || utilJs.isIOSAppALL() ? '预约成功' : '设置成功，直播开始前5分钟进行微信推送提醒哦！') : '已取消提醒';
        //中泰定制 || 取消提醒，直接toast提示
        if (this.personalSet || this.setType == 2) {
          this.$showCjToast({
            text: tipText,
          });
          this.nockBottom(isbottom)
          return;
        }
        if (isbottom == 1) {
          this.nockBottom(isbottom)
          return
        }
        //显示预约成功分享弹窗
        this.showBookSuccess = true;
      }, () => {
        this._isClicking = false;
      });
    },
    nockBottom(isbottom) {
      if (isbottom == 1) {
        console.log(222222222)
        if (this.goLiveRoom) {
          console.log(11111111111)
          this.goLiveRoom()
        }
        return
      }
    },
    initData() {
      this.buySwiperList = [];
      this.liveStartDownCount =
      this.showBuySwiper = false;
      this.personalSet = false;
      this.showBookSuccess = false;
      this.isPlayingVideo = false;
      this.isPlayEndVideo = false;
      this._isClicking = false;
      this._liveTimeCon = null;
      let curCompanyId = localStorage.getItem('companyId');
      let setpersonal = ['79jee7', 'lj7l', '5r4y7'];//中泰定制
      if (setpersonal.includes(curCompanyId)) {
        this.personalSet = true
      }
    },
    public_initDetail(info = {}) {
      this.initData();
      this.prodInfo = {
        prodId: info.prodId, //直播id
        cover: info.cover,
        payType: info.payType,
        isShowRemind: info.isShowRemind, //是否开启预约
        liveStatus: info.liveStatus,
        videoIntroUrl: info.videoIntroUrl || '', //视频简介
        videoIntroM3u8: info.videoIntroM3u8 || '',
        startAt: info.startAt || '', //直播开始时间
      };
      this.getLiveRemind();
      this.initStartLiveTime();
      //是否开启购买信息展示
      let enableBuyedInfoSwiper = localStorage.getItem("cfg") && JSON.parse(localStorage.getItem("cfg")) && JSON.parse(localStorage.getItem("cfg")).enableBuyedInfoSwiper || 0;
      if (this.moduleType == 1 && enableBuyedInfoSwiper && this.prodInfo.payType == 2) {
        this.buyedInfoSwiper();
      }
      this.$nextTick(() => {
        this.initVideoPlayer();
      })

    },
  //开始直播倒计时
    initStartLiveTime() {
      //直播间没有开始直播倒计时
      if (this.moduleType == 2) {
        return;
      }
      //直播已开始，不显示倒计时
      if (this.prodInfo.liveStatus > 0) {
        return;
      }
      let liveTimeTmp = new Date(this.prodInfo.startAt.replace(/-/g, '/')).getTime();
      clearInterval(this._liveTimeCon);
      this._liveTimeCon = setInterval(() => {
        let nowTmp = new Date().getTime();
        let subTimeTmp = liveTimeTmp - nowTmp;
        //直播已开始
        if (subTimeTmp < 0) {
          clearInterval(this._liveTimeCon);
          this.liveStartDownCount = null;
          return;
        }
        if (subTimeTmp < 5 * 60 * 1000) {
          this.prodInfo.isShowRemind = false;
          this.$emit('upDateisShowFixedBook', this.prodInfo.isShowRemind)
        }
        let timeObj = utilJs.timeTmpToStr(Math.abs(subTimeTmp), true);
        timeObj.dayNum = timeObj.dayNum == -1 ? '00' : timeObj.dayNum < 10 ? `0${timeObj.dayNum}` : timeObj.dayNum;
        timeObj.hourNum = timeObj.hourNum == -1 ? '00' : timeObj.hourNum < 10 ? `0${timeObj.hourNum}` : timeObj.hourNum;
        timeObj.minuteNum = timeObj.minuteNum == -1 ? '00' : timeObj.minuteNum < 10 ? `0${timeObj.minuteNum}` : timeObj.minuteNum;
        timeObj.secondsNum = timeObj.secondsNum < 10 ? `0${timeObj.secondsNum}` : timeObj.secondsNum;
        this.liveStartDownCount = timeObj;

      }, 1000);
    },
    //购买信息
    buyedInfoSwiper() {
      utilJs.getMethod(`${global.apiurl}common/buyedInfoSwiper?prodId=${this.prodInfo.prodId}&prodType=${global.ckFrom.live}`, (res) => {
        this.buySwiperList = res || [];
        //购买人数>2 && 付费的
        this.showBuySwiper = this.buySwiperList.length > 2;
      });
    },
    async clickLiveCover() {
      if (this.prodInfo && this.prodInfo.videoIntroUrl) {
        this.isPlayingVideo = true;
        this.isPlayEndVideo = false
        this.tcPlayer.play();

      }
    },
    //初始化视频介绍播放器
    initVideoPlayer() {
      if (!this.prodInfo.videoIntroUrl) {
        return;
      }
      if (this.tcPlayer) {
        this.tcPlayer.destroy();
        this.tcPlayer = null;
      }
      let videoObj = {
        videoMp4: this.prodInfo.videoIntroUrl,
        videoM3U8: this.prodInfo.videoIntroM3u8 || this.prodInfo.videoIntroUrl,
        autoplay: true,
        fluid: false,
        isCssFullScreen: true,
        loop:false
      };
      this.tcPlayer = getXgplayer("liveVideoIntroParent", videoObj);
      this.tcPlayer.on("play", () => {
        if (this.prodInfo && this.prodInfo.videoIntroUrl) {
          this.isPlayingVideo = true;
          this.isPlayEndVideo = false
        }
      })
      this.tcPlayer.on("ended", () => {
        console.log(222222222222222)
        if (this.prodInfo && this.prodInfo.videoIntroUrl) {
          this.isPlayingVideo = false
          this.isPlayEndVideo = true;
          this.tcPlayer.exitFullscreen()
        }
      })
    },
  },
  deactivated() {
    this.prodInfo = null;
    if (this.tcPlayer) {
      destoryPlayer(this.tcPlayer);
      this.tcPlayer = null;
    }
  },
  destroyed() {
    this.prodInfo = null;
    if (this.tcPlayer) {
 destoryPlayer(this.tcPlayer);
      this.tcPlayer = null;
    }
  }
}
</script>
<style scoped lang="scss">
.promote-bg {
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0 1px 5px 0 #0000001a;
}
.live-start {
  .c-bg-xblue {
    background: var(--live-theme-color);
  }
}
</style>